//
//  HJChatUserManager.m
//  KaiChat
//
//  Created by lx on 2023/10/20.
//

#import "HJChatUserManager.h"
#import "HJChatFriendModel.h"
#import "HJIM.h"

@implementation HJChatUserManager

- (void)getFriendListsComplete:(void (^)(NSArray<HJChatFriendModel *> * _Nullable datas))complete {
    
    [HJChatFriendModel bg_findAllAsync:[HJChatFriendModel bg_tableName] complete:^(NSArray * _Nullable array) {
        if (array.count) {
            dispatch_async_main_queue(^{
                complete(array);
            });
        }
    }];
    
    [HJNetworking.shareNetwork POSTBodyJSON:API_friendList parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        NSArray *list = data[@"list"];
        NSMutableArray *friendUserIds = [NSMutableArray array];
        NSMutableArray *datas = [NSMutableArray arrayWithCapacity:list.count];
        NSMutableArray *userModels = [NSMutableArray arrayWithCapacity:list.count];
        
        HJChatFriendModel *friendModel = nil;
        
        for (NSDictionary *dict in list) {
            friendModel = [HJChatFriendModel modelWithDict:dict];
            [friendUserIds addObject:friendModel.userId];
            [datas addObject:friendModel];
            [userModels addObject:[HJChatUserModel modelWithFriendModel:friendModel]];
        }
        !complete ?: complete(datas);
        
        [HJChatFriendModel bg_findAllAsync:[HJChatFriendModel bg_tableName] complete:^(NSArray * _Nullable array) {
            
            [HJChatFriendModel bg_delete:[HJChatFriendModel bg_tableName] where:[NSString stringWithFormat:@"where %@ is null", bg_sqlKey(@"userId")]];
            [HJChatUserModel bg_delete:[HJChatUserModel bg_tableName] where:[NSString stringWithFormat:@"where %@ is null", bg_sqlKey(@"userId")]];
            
            [array enumerateObjectsUsingBlock:^(HJChatFriendModel *  _Nonnull obj, NSUInteger idx, BOOL * _Nonnull stop) {
                if (![friendUserIds containsObject:obj.userId]) {
                    [HJChatFriendModel bg_delete:[HJChatFriendModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(obj.userId)]];
                    [HJChatUserModel bg_delete:[HJChatUserModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(obj.userId)]];
                } else if ([HJUserInfo.userId isEqualToString:obj.userId]) {
                    [HJChatFriendModel bg_delete:[HJChatFriendModel bg_tableName] where:[NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(obj.userId)]];
                }
            }];
            
            [HJChatFriendModel bg_saveOrUpdateArray:datas];
            [HJChatUserModel bg_saveOrUpdateArray:userModels];
        }];
    } failure:^(NSError * _Nonnull error) {
        
    }];
}

- (void)loadFriendInfoWithUserId:(NSString *)userId complete:(void (^)(HJChatFriendModel * _Nullable model))complete {
    
    if (isEmptyString(userId)) return;
    
    [HJNetworking.shareNetwork POSTBodyJSON:API_friendInfo parameters:@{
        @"friend_id": userId
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatFriendModel *model = [HJChatFriendModel modelWithDict:data[@"user_info"]];
        model.userId = userId;
        !complete ?: complete(model);
        [model bg_saveOrUpdateAsync:nil];
        
        HJChatUserModel *userModel = [HJChatUserModel modelWithFriendModel:model];
        [userModel bg_saveOrUpdateAsync:nil];
        
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(nil);
    }];
}

- (void)loadUserInfoWithUserId:(NSString *)userId complete:(void (^)(HJChatUserModel * _Nullable model))complete {
    
    if (isEmptyString(userId)) return;
    
    [HJNetworking.shareNetwork GET:API_userInfo parameters:@{
        @"user_id": userId
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        HJChatUserModel *model = [HJChatUserModel modelWithDict:data];
        model.userId = userId;
        !complete ?: complete(model);
        [model bg_saveOrUpdateAsync:nil];
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(nil);
    }];
}



- (void)loadUserApplyListDataComplete:(void (^)(NSArray <NSArray <HJUserApplyModel *>*>* _Nullable datas, HJLoadType loadType))complete {
    
    //当前时间大于3天的, 按时间排序
    //当前时间小于3天的  按时间排序
    
    NSInteger timestamp = [[NSDate date] dateByAddingDays:-3].timestamp;
    
    dispatch_async_serial_queue(^{
        
        NSArray *newDatas = [HJUserApplyModel bg_find:[HJUserApplyModel bg_tableName] where:[NSString stringWithFormat:@"where %@>%@ order by BG_date desc", bg_sqlKey(@"date"),bg_sqlValue(@(timestamp))]];
        NSArray *oldDatas = [HJUserApplyModel bg_find:[HJUserApplyModel bg_tableName] where:[NSString stringWithFormat:@"where %@<=%@ order by BG_date desc", bg_sqlKey(@"date"),bg_sqlValue(@(timestamp))]];
        if (!newDatas) newDatas = @[];
        if (!oldDatas) oldDatas = @[];
        
        dispatch_async_main_queue(^{
            !complete ?: complete(@[newDatas, oldDatas], HJLoadTypeCache);
        });
        
    });
    
    [HJNetworking.shareNetwork GET:API_applyList parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        
        dispatch_async_serial_queue(^{
            
            NSMutableArray *datas = [NSMutableArray array];
            NSArray *news = [HJUserApplyModel mj_objectArrayWithKeyValuesArray:data[@"news"]];
            NSArray *olds = [HJUserApplyModel mj_objectArrayWithKeyValuesArray:data[@"olds"]];
            [datas addObjectsFromArray:news];
            [datas addObjectsFromArray:olds];
            
            NSArray *itemsSortedArray = [datas sortedArrayUsingDescriptors:@[
                [NSSortDescriptor sortDescriptorWithKey:@"date" ascending:NO],
            ]];
            
            [HJUserApplyModel bg_clear:[HJUserApplyModel bg_tableName]];
            [HJUserApplyModel bg_saveOrUpdateArray:itemsSortedArray];
            
            NSMutableArray *newDatas = [NSMutableArray array];
            NSMutableArray *oldDatas = [NSMutableArray array];
            
            for (HJUserApplyModel *model in itemsSortedArray) {
                if (model.date.integerValue >= timestamp) {
                    [newDatas addObject:model];
                } else {
                    [oldDatas addObject:model];
                }
            }
            
            dispatch_async_main_queue(^{
                !complete ?: complete(@[newDatas, oldDatas], HJLoadTypeNetwork);
            });
        });
        
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(nil, HJLoadTypeNetwork);
    }];
}

- (void)sendApplyAddFriendWithUserId:(NSString *)userId complete:(void (^)(NSError * _Nullable error))complete {
    [HJNetworking.shareNetwork POSTBodyJSON:API_applyAddFriend parameters:@{
        @"fid": userId
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !complete ?: complete(nil);
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(error);
    }];
}

- (void)handleFriendAddWithUserId:(NSString *)userId accept:(BOOL)accept complete:(void (^)(NSString * _Nullable sessionId))complete {
    [HJNetworking.shareNetwork POSTBodyJSON:API_comfirmAddFriend parameters:@{
        @"fid": userId,
        @"type": toString(@(accept))
    } success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        !complete ?: complete(data[@"session_id"]);
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(nil);
    }];
}

- (void)searchFridendWithKeyword:(NSString *)keyword complete:(void (^)(HJChatUserModel * _Nullable model))complete {
    NSMutableDictionary *parameters = [NSMutableDictionary dictionary];
    [parameters setValue:keyword forKey:@"keyword"];
    [HJNetworking.shareNetwork GET:API_searchUser parameters:parameters success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        NSArray *list = data[@"list"];
        if ([list isKindOfClass:NSArray.class] && list.count) {
            HJChatUserModel *model = [HJChatUserModel modelWithDict:list.firstObject];
            !complete ?: complete(model);
        } else {
            !complete ?: complete(nil);
        }
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(nil);
    }];
}


- (void)queryFriendInfoByFriendId:(NSString *)friendId completion:(void (^)(HJChatFriendModel * _Nullable userModel))completion {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(friendId)];
    [HJChatFriendModel bg_findAsync:[HJChatFriendModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
        if (completion) {
            completion(array.firstObject);
        }
    }];
}

- (void)queryFriendInfoWithUserId:(NSString *)userId complete:(void (^)(HJChatFriendModel * _Nullable model))complete {
    HJChatFriendModel *chatFriendModel = [self queryFriendInfoByFriendId:userId];
    if (chatFriendModel) {
        complete(chatFriendModel);
    } else {
        [self loadFriendInfoWithUserId:userId complete:complete];
    }
}

- (void)queryUserInfoWithUserId:(NSString *)userId complete:(void (^)(HJChatUserModel * _Nullable model))complete {
    dispatch_async_sql_queue(^{
        HJChatUserModel *chatUserModel = [self queryUserInfoByUserId:userId];
        if (chatUserModel) {
            dispatch_async_main_queue(^{
                complete(chatUserModel);
            });
        } else {
            [self loadUserInfoWithUserId:userId complete:complete];
        }
    });
 
}

- (HJChatFriendModel *)queryFriendInfoByFriendId:(NSString *)friendId  {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(friendId)];
    return [HJChatFriendModel bg_find:[HJChatFriendModel bg_tableName] where:where].lastObject;
}


- (void)queryUserInfoByFriendId:(NSString *)friendId completion:(void (^)(HJChatUserModel * _Nullable userModel))completion {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(friendId)];
    [HJChatUserModel bg_findAsync:[HJChatUserModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
        if (completion) {
            completion(array.firstObject);
        }
    }];
}

- (HJChatUserModel *)queryUserInfoByUserId:(NSString *)userId {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"userId"),bg_sqlValue(userId)];
    return [HJChatUserModel bg_find:[HJChatUserModel bg_tableName] where:where].lastObject;
}

- (HJChatUserModel *)queryUserInfoByUid:(NSString *)uid {
    NSString *where = [NSString stringWithFormat:@"where %@=%@", bg_sqlKey(@"uid"),bg_sqlValue(uid)];
    return [HJChatUserModel bg_find:[HJChatUserModel bg_tableName] where:where].lastObject;
}

- (void)searchFriendByKeyword:(NSString *)keyword completion:(void (^)( NSArray <HJChatFriendModel *>* _Nullable datas))completion {
    NSString * where = [NSString stringWithFormat:@"where (%@ like '%%%@%%') ",bg_sqlKey(@"nickname"),keyword];
    [HJChatFriendModel bg_findAsync:[HJChatFriendModel bg_tableName] where:where complete:^(NSArray * _Nullable array) {
        !completion ?: completion(array);
    }];
}

- (void)loadApplyCountComplete:(void (^__nullable)(NSInteger count))complete {
    [HJNetworking.shareNetwork GET:API_applyCount parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        NSInteger num =  [data[@"num"] intValue];
        [[NSNotificationCenter defaultCenter] postNotificationName:userApplyCountChangeNotification object:@(num)];
        [HJIM.shareIM.userManager queryUserInfoWithUserId:HJUserInfo.userId complete:^(HJChatUserModel * _Nullable model) {
            model.applyCount = toString(@(num));
            [model bg_saveOrUpdate];
        }];
        !complete ?: complete(num);
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(0);
    }];
}

- (void)clearApplyCountComplete:(void (^__nullable)(NSError *error))complete {
    [HJNetworking.shareNetwork POSTBodyJSON:API_applyCountReset parameters:nil success:^(NSDictionary * _Nonnull responseObject, id  _Nonnull data) {
        [[NSNotificationCenter defaultCenter] postNotificationName:userApplyCountChangeNotification object:@(0)];
        [HJIM.shareIM.userManager queryUserInfoWithUserId:HJUserInfo.userId complete:^(HJChatUserModel * _Nullable model) {
            model.applyCount = toString(@(0));
            [model bg_saveOrUpdate];
        }];
        !complete ?: complete(nil);
    } failure:^(NSError * _Nonnull error) {
        !complete ?: complete(error);
    }];
}


@end
